package com.simplefan.system.client.web.dorado.fileloader;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import org.apache.commons.lang.ObjectUtils;

import com.bstek.dorado.common.Setting;
import com.bstek.dorado.common.fileloader.FileLoader;

/**
 * 
 * @author steven.zheng@bstek.com
 *
 */

public class MultiPathFileLoader extends FileLoader {
	private String[] roots;
	private String filePath;
	private FileLoader realFileLoader;

	public MultiPathFileLoader(String root) {
		super(root);
		roots = getRoot().split(";");
	}

	@Override
	protected void doSetFile(String filePath) {
		this.filePath = filePath;
		realFileLoader = null;
	}

	@SuppressWarnings("deprecation")
	protected FileLoader getRealFileLoader() throws FileNotFoundException,
			IOException {
		if (realFileLoader == null) {
			for (int i = 0; i < roots.length; i++) {
				FileLoader loader = new com.bstek.dorado.common.fileloader.PathFileLoader(roots[i]);
				loader.setFile(filePath);
				if (loader.exists()) {
					realFileLoader = loader;
					return realFileLoader;
				}
			}
			if (realFileLoader == null) {
				for (int i = 0; i < roots.length; i++) {
					if(ObjectUtils.equals(Setting.getString("configFileLoader.root"), roots[i]))
	                    root = "doradohome";
	                else
	                    root = "";
					FileLoader loader = new com.bstek.dorado.common.fileloader.ResourceFileLoader(root);
					loader.setFile(filePath);
					if (loader.exists()) {
						realFileLoader = loader;
						return realFileLoader;
					}
				}
			}
			if (realFileLoader == null) {
				throw new FileNotFoundException("[" + filePath
						+ "] not exists.");
			}
		}
		return realFileLoader;
	}

	@Override
	public boolean exists() {
		try {
			return getRealFileLoader().exists();
		} catch (Exception ex) {
			return false;
		}
	}

	@Override
	public InputStream getInputStream() throws IOException {
		return getRealFileLoader().getInputStream();
	}

	@Override
	public long getLastModified() throws IOException {
		return getRealFileLoader().getLastModified();
	}

	@Override
	public OutputStream getOutputStream() throws IOException {
		return getRealFileLoader().getOutputStream();
	}

	@Override
	public String getRealPath() {
		try {
			return getRealFileLoader().getRealPath();
		} catch (FileNotFoundException ex) {
			return null;
		} catch (IOException ex) {
			return null;
		}
	}

	@Override
	public URL getURL() throws FileNotFoundException, IOException {
		return getRealFileLoader().getURL();
	}
}
